package com.skong.report.extend;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;

public class TokenRequestWrapper extends HttpServletRequestWrapper {

    private final Logger logger= LoggerFactory.getLogger(getClass());

    RestTemplate restTemplate;

    TokenRequestWrapper(HttpServletRequest request, RestTemplate restTemplate) {
        super(request);
        this.restTemplate=restTemplate;
    }
    /**
     * 修改此方法主要是因为当RequestMapper中的参数为pojo类型时，
     * 会通过此方法获取所有的请求参数并进行遍历，对pojo属性赋值
     * @return
     */
    @Override
    public Enumeration<String> getParameterNames() {
        Enumeration<String> enumeration = super.getParameterNames();
        ArrayList<String> list = Collections.list(enumeration);
        //当有token字段时动态的添加uid字段
        if (list.contains("token")){
            return Collections.enumeration(TokenUtil.getParameterNames());
        }else {
            return super.getParameterNames();
        }
    }
    @Override
    public String getParameter(String name) {
        if ("tenant_id".equals(name)){
            return TokenUtil.getParameterValues(restTemplate,getParameter("token")).get("tenant_id");
        }
        if ("org_code".equals(name)){
            return TokenUtil.getParameterValues(restTemplate,getParameter("token")).get("org_code");
        }
        if ("current_user_id".equals(name)){
            return TokenUtil.getParameterValues(restTemplate,getParameter("token")).get("current_user_id");
        }
        if ("current_user_name".equals(name)){
            return TokenUtil.getParameterValues(restTemplate,getParameter("token")).get("current_user_name");
        }
        return super.getParameter(name);
    }
}